package cn.edu.zjicm.wordsnet_d.synchronize;

import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

public abstract class TripleDES {

    public static final String  ALGORITHM    = "DESede";

    private static final char[] DIGITS_LOWER = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

    public abstract Key getTripledesKey();

    /**
     * 获取可用的Cipher
     * 
     * @param cipherMode Cipher.ENCRYPT_MODE/Cipher.DECRYPT_MODE
     * @return 可用的Cipher
     */
    private Cipher getCipher(int cipherMode) {
        Cipher cipher = null;
        try {
            cipher = Cipher.getInstance(ALGORITHM);
        } catch (NoSuchAlgorithmException e) {
            System.err.println("Cipher initialize Error! NoSuchAlgorithmException.");
        } catch (NoSuchPaddingException e) {
            System.err.println("Cipher initialize Error! NoSuchPaddingException.");
        }
        if (cipher == null) {
            System.err.println("Cipher initialize Error! Cipher is null.");
            return cipher;
        }

        try {
            cipher.init(cipherMode, getTripledesKey());
        } catch (InvalidKeyException e) {
            System.err.println("Cipher initialize Error! InvalidKeyException.");
            return null;
        }
        return cipher;
    }

    /**
     * 加密字符串
     * 
     * @param plainString 明文
     * @return 密文
     */
    public String encrypt(String plainString) {
        if (plainString == null) {
            return null;
        }
        //加密               
        Cipher cipher = getCipher(Cipher.ENCRYPT_MODE);
        byte[] encryptedBytes = null;
        //System.out.println("encrypt default charset(TripleDES):" + Charset.defaultCharset().name());
        try {
            encryptedBytes = cipher.doFinal(plainString.getBytes());
        } catch (IllegalBlockSizeException e) {
            System.err.println("Encrypt Error! IllegalBlockSizeException.");
            return null;
        } catch (BadPaddingException e) {
            System.err.println("Encrypt Error! BadPaddingException.");
            return null;
        }
        if (encryptedBytes == null) {
            return null;
        }
        return encodeHex(encryptedBytes, DIGITS_LOWER);
    }

    private static String encodeHex(byte[] data, char[] toDigits) {
        int l = data.length;
        char[] out = new char[l << 1];
        // two characters form the hex value.
        for (int i = 0, j = 0; i < l; i++) {
            out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
            out[j++] = toDigits[0x0F & data[i]];
        }
        return String.valueOf(out);
    }

    /**
     * 解密字符串
     * 
     * @param cryptString 密文
     * @return 明文
     */
    public String decrypt(String cryptString) {
        if (cryptString == null) {
            return null;
        }
        Cipher cipher = getCipher(Cipher.DECRYPT_MODE);
        byte[] decryptedBytes = null;
        try {
            byte[] encryptedBytes = decodeHex(cryptString.toCharArray());
            decryptedBytes = cipher.doFinal(encryptedBytes);
        } catch (IllegalBlockSizeException e) {
            System.err.println("Encrypt Error! IllegalBlockSizeException.");
            return null;
        } catch (BadPaddingException e) {
            System.err.println("Encrypt Error! BadPaddingException.");
            return null;
        }
        if (decryptedBytes == null) {
            return null;
        }
        //System.out.println("decrypt default charset(TripleDES):" + Charset.defaultCharset().name());
        return new String(decryptedBytes);
    }

    private static byte[] decodeHex(char[] data) throws IllegalBlockSizeException {

        int len = data.length;

        if ((len & 0x01) != 0) {
            throw new IllegalBlockSizeException("Odd number of characters.");
        }

        byte[] out = new byte[len >> 1];

        // two characters form the hex value.
        for (int i = 0, j = 0; j < len; i++) {
            int f = toDigit(data[j], j) << 4;
            j++;
            f = f | toDigit(data[j], j);
            j++;
            out[i] = (byte) (f & 0xFF);
        }

        return out;
    }

    private static int toDigit(char ch, int index) throws IllegalBlockSizeException {
        int digit = Character.digit(ch, 16);
        if (digit == -1) {
            throw new IllegalBlockSizeException("Illegal hexadecimal charcter " + ch + " at index " + index);
        }
        return digit;
    }
}
